package com.xie.o2o.service.impl;

import com.google.common.collect.Lists;
import com.xie.o2o.dao.ProductDao;
import com.xie.o2o.dao.ProductImgDao;
import com.xie.o2o.dto.ProductExecution;
import com.xie.o2o.entity.Product;
import com.xie.o2o.entity.ProductImg;
import com.xie.o2o.enums.ProductStateEnum;
import com.xie.o2o.service.ProductService;
import com.xie.o2o.util.ImageUtil;
import com.xie.o2o.util.PageCalculator;
import com.xie.o2o.util.PathUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

/**
 * @create: xie
 */
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductDao productDao;

    @Autowired
    private ProductImgDao productImgDao;


    /**
     * 添加商品
     * 1.处理缩略图，获取缩略图相对路径副职给product
     * 2.往tb_product写入商品信息，获取productid
     * 3.根据productid批量处理详情图
     * 4.将商品详情图批量插入tb_product_img
     *
     * @param product  商品信息
     * @param file     缩略图
     * @param fileList 商品详情图
     * @return
     * @throws RuntimeException
     */
    @Override
    @Transactional
    public ProductExecution addProduct(Product product, MultipartFile file, List<MultipartFile> fileList) throws RuntimeException {
        if (product != null && product.getShop() != null && product.getShop().getShopId() != null) {
            //设置默认属性
            product.setCreateTime(new Date());
            product.setLastEditTime(new Date());
            //默认上架状态
            product.setEnableStatus(1);
            //添加缩略图
            addThumbnail(product, file);
            productDao.insertProduct(product);
            //处理详情图
            addProductImgList(product, fileList);
            return new ProductExecution(ProductStateEnum.SUCCESS, product);
        } else {
            //传参为空返回空值错误
            return new ProductExecution(ProductStateEnum.EMPTY);
        }
    }

    @Override
    public Product getProductById(long productId) {
        return productDao.queryProductById(productId);
    }

    /**
     * 修改商品信息
     *
     * @param product
     * @param file
     * @param fileList
     * @return
     * @throws RuntimeException
     */
    @Override
    @Transactional
    public ProductExecution modifyProduct(Product product, MultipartFile file, List<MultipartFile> fileList) throws RuntimeException {
        if (product != null && product.getShop() != null && product.getShop().getShopId() != null) {
            //设置默认属性
            product.setLastEditTime(new Date());
            //缩略图不为空则删除原缩略图，并添加新的
            if (file != null) {
                //获取原图片并删除
                Product tempProduct = productDao.queryProductById(product.getProductId());
                if (tempProduct.getImgAddr() != null) {
                    ImageUtil.deleteFileOrPath(tempProduct.getImgAddr());
                }
                //添加新图片
                addThumbnail(product, file);
            }
            //详情图不为空则删除原详情图，并添加新的
            if (fileList != null && fileList.size() > 0) {
                deleteProductImgList(product.getProductId());
                addProductImgList(product, fileList);
            }
            //更新商品信息
            productDao.updateProduct(product);
            return new ProductExecution(ProductStateEnum.SUCCESS, product);
        } else {
            return new ProductExecution(ProductStateEnum.EMPTY);
        }
    }

    /**
     * 获取商品列表
     *
     * @param product
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @Override
    public ProductExecution getProductList(Product product, int pageIndex, int pageSize) {
        //页码转行成数据库行码
        int rowIndex = PageCalculator.calculateRowIndex(pageIndex, pageSize);
        List<Product> products = productDao.queryProductList(product, rowIndex, pageSize);
        //基于相同条件下查询的商品总数
        int count = productDao.queryProductCount(product);
        ProductExecution pe = new ProductExecution();
        pe.setProductList(products);
        pe.setProductCount(count);
        return pe;
    }

    /**
     * 删除商品详情图
     *
     * @param productId
     */
    private void deleteProductImgList(Long productId) {
        //根据productId查询图片
        List<ProductImg> list = productImgDao.queryProductImgList(productId);
        for (ProductImg productImg : list) {
            //循环删除
            ImageUtil.deleteFileOrPath(productImg.getImgAddr());
        }
        //删除数据库里的图片地址
        productImgDao.deleteProductImgByProductId(productId);
    }

    /**
     * 批量添加商品详情图
     *
     * @param product
     * @param fileList
     */
    private void addProductImgList(Product product, List<MultipartFile> fileList) {
        //获取文件路径，存到对应店铺的文件夹下
        String dest = PathUtil.getShopImgPath(product.getShop().getShopId());
        List<ProductImg> imgList = Lists.newArrayList();
        //遍历处理每一张详情图
        for (MultipartFile file : fileList) {
            //压缩处理图片
            String imgAddr = ImageUtil.generateNormalImg(file, dest);
            ProductImg productImg = new ProductImg();
            productImg.setImgAddr(imgAddr);
            productImg.setImgDesc(product.getProductName());
            productImg.setProductId(product.getProductId());
            productImg.setCreateTime(new Date());
            imgList.add(productImg);
        }
        //确实有图片添加
        if (imgList.size() > 0) {
            try {
                int i = productImgDao.batchInsertProductImg(imgList);
                if (i <= 0) {
                    throw new RuntimeException("添加商品详情图失败");
                }
            } catch (Exception e) {
                throw new RuntimeException("添加商品详情图失败:" + e.getMessage());
            }
        }
    }

    /**
     * 添加缩略图
     *
     * @param product
     * @param file
     */
    private void addThumbnail(Product product, MultipartFile file) {
        String dest = PathUtil.getShopImgPath(product.getShop().getShopId());
        String thumbnailAddr = ImageUtil.generateThumbnail(file, dest);
        product.setImgAddr(thumbnailAddr);
    }

}
